package manager.rank;

import java.awt.RenderingHints.Key;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.MidiChannel;

import org.apache.jute.Index;
import org.springframework.cglib.core.Local;

import com.alibaba.dubbo.rpc.Result;

import net.socket.server.request.LocalPlayResultRequest;
import net.socket.server.response.LocalPlayResultResponse;
import redis.clients.jedis.Jedis;
import util.MyFactory;
import util.RedisUtil;
import util.RedisUtilKS;

public class InsertToRedis {
	private static List<String> Result = null;
	private Jedis myJedis =null;

	/**
	 * 插入redis并且返回本次唱歌的单曲排名
	 * @param req
	 */
	@SuppressWarnings("finally")
	
	public int[]  insertRedisSongRankAndReturnThisRankNew(LocalPlayResultRequest req) {
		String mid = Integer.toString(req.getMachineId());
		String songId = req.getSongId();
		//String openId = req.getOpenId();
		int [] ranks= new int[2];
		int score = req.getScore();
		String Kbox_MAX_Rank_key =String.format("kbox:max:rank:%s",songId);
		String Kbox_THE_Rank_key =String.format("kbox:the:rank:%s:%s",mid,songId); 
		String union_key = String.format("%d%s",System.currentTimeMillis(),mid);
		myJedis = MyFactory.context.getBean("RedisUtilKS", RedisUtilKS.class).getJedis();


		myJedis.zadd(Kbox_MAX_Rank_key,score,union_key);
		myJedis.zadd(Kbox_THE_Rank_key,score,union_key);

		System.out.println(union_key);
		ranks[0]  = myJedis.zrevrank(Kbox_MAX_Rank_key, union_key).intValue()+1;
		ranks[1] = myJedis.zrevrank(Kbox_THE_Rank_key, union_key).intValue()+1;
		System.out.println(myJedis.zrevrange(Kbox_THE_Rank_key, 0, -1));
		System.out.println(ranks[0]);
		return ranks;
	}
//	public static void main(String[] args) {
//		LocalPlayResultRequest req = new LocalPlayResultRequest();
//		req.setMachineId(43);
//		req.setScore(101);
//		req.setSongId("ksmk111606");
//		System.out.println("1____");
//		MyFactory.context.getBean("InsertToRedis",InsertToRedis.class).insertRedisSongRankAndReturnThisRankNew(req);
//	}
	
	public List<String> playResultSonglistKey(int mid,String songid){
		String mid_songlist_key = String.format("kbox:mid:songlist:%d",mid);
		
		String kbox_mode_key = String.format("kbox:mode:%d",mid);
		try {
			myJedis.del(kbox_mode_key);
			System.out.println("playResultsonglistkey________");
			myJedis = MyFactory.context.getBean("RedisUtilKS", RedisUtilKS.class).getJedis();
			String popSongid = myJedis.lpop(mid_songlist_key);
			if (!popSongid.equals(songid)) {
				System.out.println("删除的第一个元素不是结束歌曲 查找删除。");
				myJedis.lrem(mid_songlist_key,1,songid);
			}else {
				System.out.println("删除的就是结束歌曲");
			}
		}catch (Exception e) {
			System.out.println("insertRedis get a Exception---"+e);
		}finally {
			if(null != myJedis)
				myJedis.close(); // 释放资源还给连接池
			return Result;
		}
	}
	
	public List<String> cleanSonglistKey(int mid,int index) {
		String mid_songlist_key = String.format("kbox:mid:songlist:%d",mid);
		String kbox_mode_key = String.format("kbox:mode:%d",mid);
		try {
			System.out.println("cleanSonglistKey__________________1");
			myJedis = MyFactory.context.getBean("RedisUtilKS", RedisUtilKS.class).getJedis();
			myJedis.del(kbox_mode_key);
			if(-2 == index) {
				System.out.println("cleanSonglistKey__________________------query");
				Result = (ArrayList<String>) myJedis.lrange(mid_songlist_key, 0, -1);
			}
			else if (-1 == index) { 
				System.out.println("cleanSonglistKey__________________------clean");
			
				myJedis.del(mid_songlist_key);
			}
			else {
				System.out.println("cleanSonglistKey__________________------clean 1");
				myJedis.lpop(mid_songlist_key);
				
			}
			
		}catch (Exception e) {
			System.out.println("insertRedis get a Exception---"+e);
		}finally {
			if(null != myJedis)
				myJedis.close(); // 释放资源还给连接池
			return Result;
		}
	}
	
	public int[]  insertRedisSongRankAndReturnThisRank(LocalPlayResultRequest req) {
		String mid = Integer.toString(req.getMachineId());
		String songId = req.getSongId();
		String openId = req.getOpenId();
		int [] ranks= new int[2];
		int score = req.getScore();
		double beforeScore;
		 try {
			 myJedis = MyFactory.context.getBean("RedisUtil", RedisUtil.class).getJedis();
			 myJedis.zincrby("vod:SingTimesRank", 1, openId);//唱歌次数的排行榜(总榜）
			 myJedis.zincrby("vod:SingTimesRank:" + mid, 1, openId);//唱歌次数排行榜（机器榜）
			 
			 //唱过的歌曲排行榜（唱了多少首不同的歌）
			 //判断songId是不是已经被openId唱过，如果没唱过，加入set里面，并且在sorted set里面将对应的openId唱过的歌曲数加1
			 if(myJedis.sismember("vod:SingSongSet:"+openId, songId)==false ) {
				 myJedis.sadd("vod:SingSongSet:"+openId, songId);
				 myJedis.zincrby("vod:SongNumRank", 1, openId);
			 }
			 //单机榜
			 if(myJedis.sismember("vod:SingSongSet:"+openId+":"+mid, songId)==false ) {
				 myJedis.sadd("vod:SingSongSet:"+openId+":"+mid, songId);
				 myJedis.zincrby("vod:SongNumRank:"+mid, 1, openId);
			 }
			 
			 //单曲得分榜:如果为null，表示此人以前没唱过这首歌，则将其放入，此时返回的排名就是本次的排名
			 if(null == myJedis.zscore("vod:SingleSongScoreRank:"+songId, openId)){
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId, score, openId);
				 ranks[0] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId, openId).intValue()+1;
			 }else{
				beforeScore = myJedis.zscore("vod:SingleSongScoreRank:"+songId, openId);
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId, score, openId);
				 ranks[0] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId, openId).intValue()+1+1;
				 //如果以前的最大分数大于本次的，还要将以前的分数换回去
				 if(beforeScore >(double)score) 
					 myJedis.zadd("vod:SingleSongScoreRank:"+songId, beforeScore, openId);
				 else
					ranks[0]--;
				
			 }
			 //单机榜，如果不等于null，则只有当以前的分数小于本次的才放到redis里
			 if(null ==myJedis.zscore("vod:SingleSongScoreRank:"+songId+":"+mid, openId)) {
				myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);	
				ranks[1] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId+":"+mid,  openId).intValue()+1;
			 }else {
				 beforeScore = myJedis.zscore("vod:SingleSongScoreRank:"+songId+":"+mid, openId);
				 myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);
				 ranks[1] = myJedis.zrevrank("vod:SingleSongScoreRank:"+songId+":"+mid,  openId).intValue()+1+1;
				 if(beforeScore <(double)score) 
					 myJedis.zadd("vod:SingleSongScoreRank:"+songId+":"+mid, score, openId);
				 else
					 ranks[1]--;
			 }
			 
			 
		} catch (Exception e) {
			System.out.println("insertRedis get a Exception---"+e);
		}finally {
			if(null != myJedis)
				myJedis.close(); // 释放资源还给连接池
			return ranks;
		}
		
	}
}
